<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Overtrue\Pinyin\MemoryFileDictLoader;

class AddPinyinColumn extends Migration
{
    /**
     * @var \Overtrue\Pinyin\Pinyin
     */
    protected $pinyin;

    protected $logger;

    /**
     * AddPinyinColumn constructor.
     * @throws \Exception
     */
    public function __construct()
    {
        $this->pinyin = app('pinyin');
        $this->pinyin->setLoader(new MemoryFileDictLoader(
                app_path().'/../vendor/overtrue/pinyin/data/'
            )
        );

        $this->logger = new Logger('pinyin');
        $this->logger->pushHandler(new StreamHandler(storage_path('logs/pinyin.log')));
    }

    /**
     * Run the migrations.
     * @return void
     */
    public function up()
    {
//        Schema::table('st_cn_disease_dictionary', function (Blueprint $table) {
//            $table->string('intact_pinyin')->nullable()->after('name');
//        });
        $this->inject('st_cn_disease_dictionary', true);

//        Schema::table('st_disease_dictionary', function (Blueprint $table) {
//            $table->string('intact_pinyin')->nullable()->after('name');
//        });
        $this->inject('st_disease_dictionary', true);
    }

    /**
     * Reverse the migrations.
     * @return void
     */
    public function down()
    {
        Schema::table('st_cn_disease_dictionary', function (Blueprint $table) {
            $table->dropColumn('intact_pinyin');
            $table->dropColumn('pinyin');
        });

        Schema::table('st_disease_dictionary', function (Blueprint $table) {
            $table->dropColumn('intact_pinyin');
            $table->dropColumn('pinyin');
        });

    }

    /**
     * @param $table
     * @param $simple
     */
    protected function inject($table, $simple = false)
    {
        DB::table($table)->orderBy('id')->chunk(200, function ($drugs) use ($table, $simple) {

            foreach ($drugs as $drug) {
                $py     = $this->pinyin->convert($drug->name);
//                $update = ['intact_pinyin' => implode('', $py)];

//                if ($simple) {
                    $update['pinyin'] = implode('', array_map(function ($pinyin) {
                        return $pinyin[0];
                    }, $py));
//                }

                $result = DB::table($table)->where('id', $drug->id)->update($update);

                if ($result) {
                    echo 'success ' . $table . ' :: ' . $drug->name . "\n";
                } else {
                    $this->logger->error($table . ' :: ' . $drug->name . "  写入拼音失败。\n");
                }
            }
        });
    }
}
